<template>
    <el-row type="flex" align="middle">
        <el-avatar :size="150" src="src/assets/images/avatar.png" />
        <div style="margin-left: 20px;">
            <!-- 根据登录状态显示用户名 -->
            <p class="UserName">{{ loginStore.loginUsername || '用户名' }}</p>
            <p class="Usertxt">{{ loginStore.loginToken ? '已登录' : '个性化信息' }}</p>
        </div>
        <!-- 根据登录状态显示不同按钮 -->
        <el-button type="success" @click="dialogVisible = true" v-if="!loginStore.loginToken">登录</el-button>
        <el-button type="success" @click="loginOut()" v-else>退出</el-button>
    </el-row>
    
    <!--登录-->
    <el-dialog v-model="dialogVisible" title="Tirp" width="500">
        <!--登录表单-->
        <el-form :model="form" label-width="auto" style="max-width: 600px">
            <el-form-item label="email" style="display: flex;">
                <el-input v-model="form.email" style="flex:5;" placeholder="请输入邮箱"/>
                <!--单击事件-->
                <el-button @click="sendCode" type="success" style="flex: 1;">发送验证码</el-button>
            </el-form-item>
            <el-form-item label="code">
                <el-input v-model="form.code" placeholder="请输入验证码"/>
            </el-form-item>
        </el-form>
        <!-- 登录的表单end -->
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogVisible = false">Cancel</el-button>
                <el-button type="primary" @click="login()">Login</el-button>
            </div>
        </template>
    </el-dialog>
    
    <el-row>
        <el-menu
            :default-active="activeIndex"
            class="el-menu-demo"
            mode="horizontal"
            :ellipsis="false"
            @select="handleSelect"
        >
            <el-menu-item index="1" @click="router.push('/User')">我的翻车鱼</el-menu-item>
            <el-menu-item index="2" @click="router.push('/Useraddress')">个人信息</el-menu-item>
        </el-menu>
    </el-row>
</template>

<script lang="ts" setup>
import { ElNotification } from 'element-plus'
import router from '@/router'
import { ref, reactive } from 'vue';
import axios from '@/http/request' 
import { useLoginStore } from '@/stores/LoginStore'

// 实例化一个useLoginStore的对象
const loginStore = useLoginStore()

let dialogVisible = ref(false)
const activeIndex = ref('1')

// 表单数据
const form = reactive({
    email: '',
    code: ''
})

// 发送验证码
async function sendCode() {
    if (!form.email) {
        ElNotification({
            title: 'Error',
            message: '请输入邮箱地址',
            type: 'error',
            duration: 1000
        })
        return
    }
    
    try {
        let res = await axios.get(`/user/${form.email}`)
        if (res.data.code == 200) {
            ElNotification({
                title: 'Success',
                message: res.data.msg,
                type: 'success',
            })
        } else {
            ElNotification({
                title: 'Error',
                message: res.data.msg,
                type: 'error',
                duration: 1000
            })
        }
    } catch (error) {
        ElNotification({
            title: 'Error',
            message: '发送验证码失败',
            type: 'error',
            duration: 1000
        })
    }
}

// 登录
async function login() {
    if (!form.email || !form.code) {
        ElNotification({
            title: 'Error',
            message: '请输入邮箱和验证码',
            type: 'error',
        })
        return
    }
    
    try {
        let res = await axios.post(`/user/${form.email}/${form.code}`)
        if (res.data.code == 200) {
            ElNotification({
                title: 'Success',
                message: '登录成功',
                type: 'success',
            })
            
            // 登录成功后，关闭对话框
            dialogVisible.value = false
            
            // 获取token和username
            let token = res.data.data.token
            let username = res.data.data.username

            // pinia来存储username和token
            loginStore.setLoginInfo(username, token);
            
            // 跳转到首页
            router.push('/user')
            activeIndex.value = '1'
            
            // 清空表单
            form.email = ''
            form.code = ''
        } else {
            ElNotification({
                title: 'Error',
                message: res.data.msg,
                type: 'error',
            })
        }
    } catch (error) {
        ElNotification({
            title: 'Error',
            message: '登录失败',
            type: 'error',
        })
    }
}

// 安全退出
function loginOut() {
    // 清除pinia中的数据
    loginStore.setLoginInfo('', '')
    // 清除本地存储
    localStorage.clear()
    
    ElNotification({
        title: 'Success',
        message: '已退出登录',
        type: 'success',
    })
    
    activeIndex.value = '1'
}

// 菜单选择处理
const handleSelect = (key: string, keyPath: string[]) => {
    activeIndex.value = key
}
</script>

<style scoped>
.UserName {
    font-size: 40px;
    font-weight: bold;
    color: #333;
    margin-bottom: 5px;
}
.Usertxt {
    font-size: 20px;
    color: #666;
}

.el-row {
    margin-bottom: 20px;
}
</style>